package com.xiaoxin.dubbo.api;

import com.xiaoxin.dubbo.utils.IdWorker;
import com.xiaoxin.model.mongo.Video;
import com.xiaoxin.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker IdWorker;

    @Override
    public String save(Video video) {
        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(IdWorker.getNextId("video"));
        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    @Override
    public List<Video> findVideoByPids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").is(vids));
        return mongoTemplate.find(query, Video.class);
    }

    @Override
    public List<Video> queryList(int page, Integer pagesize) {
        Query query = new Query().skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    @Override
    public Video findByVideoId(ObjectId videoId) {
        Query query = Query.query(Criteria.where("id").is(videoId));
        return mongoTemplate.findOne(query, Video.class);
    }

    @Override
    public PageResult getUserVideos(Integer page, Integer pagesize, Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        long count = mongoTemplate.count(query, Video.class);
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page, pagesize, count, list);

    }

}